<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">

        <el-form-item label="机构">
          <el-select v-model="listQuery.departmentId" clearable placeholder="请选择" style="width: 90px;" @change="selectDepartmentId">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="停车场名称">
          <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 120px;" placeholder="停车场名称"/>
        </el-form-item>

        <!-- <el-form-item label="状态">
          <el-select v-model="listQuery.status" placeholder="请选择" style="width: 90px;">
            <el-option
              v-for="item in status_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item> -->

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:park:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <!-- <el-table-column align="center" label="停车场ID" prop="id" /> -->
      <el-table-column align="center" label="停车场名称" prop="name" />

      <el-table-column align="center" label="父停车场名称" prop="parentName"/>

      <el-table-column align="center" label="所属机构" prop="departmentName"/>

      <el-table-column align="center" label="车场地址" prop="address"/>

      <!--<el-table-column align="center" label="经纬度" prop="status">
        <template slot-scope="scope">
          <el-tag >{{ scope.row.longitude }}</el-tag>
          <el-tag >{{ scope.row.latitude }}</el-tag>
        </template>
      </el-table-column>-->

      <el-table-column align="center" label="车位数" prop="spaceCount" />
      <el-table-column align="center" label="剩余车位" prop="leftSpaceCount" />

      <!-- <el-table-column align="center" label="状态" prop="status" >
        <template slot-scope="scope">
          <el-tag >{{ getStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:park:update']"
            type="primary"
            size="small"
            @click="startEditPark(scope.row)">编辑</el-button>
            <!-- <el-button type="primary" size="small" @click="deletePark(scope.row.name, scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加停车场':'修改停车场'" :visible.sync="dialogFormVisible" width="50%">
      <!-- <span v-if="dialogType == 1">添加停车场</span>
      <span v-if="dialogType == 2">修改停车场</span>
      <hr style="margin: 1em 0 2.5em 0; border-top: 1px solid rgba(0, 0, 0, 0.1)"> -->

      <el-form ref="dialogForm" :rules="formRules" :model="dialogForm" label-width="120px">
        <el-row>
          <el-col :span="12" label-width="140px">
            <el-form-item label="新能源是否单独收费" prop="newEnergyTempRuleFlag">
              <el-select v-model="dialogForm.newEnergyTempRuleFlag" placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in danducharge"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" label-width="140px">
            <el-form-item label="黄牌车辆是否单独收费" prop="yellowLicenseTempRuleFlag">
              <el-select v-model="dialogForm.yellowLicenseTempRuleFlag" placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in danducharge"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="停车场名称  " prop="name">
              <el-input v-model="dialogForm.name" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 机构名称  " prop="departmentId">
              <el-select :disabled="dialogType != 1" clearable v-model="dialogForm.departmentId" placeholder="请选择" style="width:100%;" @change="handleDepartChange">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总车位数  " prop="spaceCount">
              <el-input v-model="dialogForm.spaceCount" onkeyup="value=value.replace(/[^\d]/g,'')" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固定车位  " prop="staticSpaceCount">
              <el-input v-model="dialogForm.staticSpaceCount" onkeyup="value=value.replace(/[^\d]/g,'')" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="临时车收费规则  " prop="tempRuleId">
              <el-select v-model="dialogForm.tempRuleId" clearable placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in tempRuleList"
                  :key="item.id"
                  :label="item.feeRuleName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 父停车场  " prop="parkId">
              <el-select v-model="dialogForm.pid" clearable placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in parkList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="  经度  " prop="longitude">
              <el-input v-model="dialogForm.longitude" onkeyup="value=value.replace(/[^\d.]/g,'')" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="  纬度  " prop="latitude">
              <el-input v-model="dialogForm.latitude" onkeyup="value=value.replace(/[^\d.]/g,'')" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="3" :push="1">
            <el-button type="primary" @click="amapSelect">获取经纬度</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属位置  " prop="area">
              <el-input v-model="dialogForm.area" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址  " prop="address">
              <el-input v-model="dialogForm.address" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="欠费是否可进  " prop="ignoreDebtTypes">
              <!-- <el-radio-group v-model="dialogForm.ignoreDebtTypes">
                <el-radio :label="1">仅内部车</el-radio>
                <el-radio :label="2">全部车辆</el-radio>
              </el-radio-group> -->
              <el-select v-model="dialogForm.ignoreDebtTypes" clearable multiple placeholder="请选择" style="width: 100%;" @change="handleChange('ignoreDebtTypes')($event)">
                <el-option :value="1" label="全部车辆"/>
                <el-option :value="2" label="内部车辆"/>
                <el-option :value="3" label="业主车辆"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可停放类型  " prop="parkingTypes">
              <!-- <el-radio-group v-model="dialogForm.onlyVip">
                <el-radio :label="true">仅内部车</el-radio>
                <el-radio :label="false">全部车辆</el-radio>
              </el-radio-group> -->
              <el-select v-model="dialogForm.parkingTypes" clearable multiple placeholder="请选择" style="width: 100%;" @change="handleChange('parkingTypes')($event)">
                <el-option v-for="(item,index) in dict.type.EParkingType" :key="index" :value="Number(item.value)" :label="item.label"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="需要合并路侧欠费记录" prop="unionPayment">
              <el-radio-group v-model="dialogForm.unionPayment">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
					<el-col :span="12">
					  <el-form-item label=" 组织  " prop="organizationId">
					    <el-select v-model="dialogForm.organizationId" clearable placeholder="请选择" >
					      <el-option
					        v-for="item in orangeList"
					        :key="item.id"
					        :label="item.name"
					        :value="item.id"/>
					    </el-select>
					  </el-form-item>
					</el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人  " prop="businessCharge">
              <el-input v-model="dialogForm.businessCharge" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话  " prop="businessPhone">
              <el-input v-model="dialogForm.businessPhone" onkeyup="value=value.replace(/[^\d-]/g,'')" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogForm.newEnergyTempRuleFlag == 1" :span="12">
            <el-form-item label="新能源收费标准">
              <el-select v-model="dialogForm.newEnergyTempRuleId" clearable placeholder="请选择新能源收费标准">
                <el-option
                  v-for="item in xnyList"
                  :key="item.id"
                  :label="item.feeRuleName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogForm.yellowLicenseTempRuleFlag == 1" :span="12">
            <el-form-item label="黄牌收费标准">
              <el-select v-model="dialogForm.yellowLicenseTempRuleId" clearable placeholder="请选择黄牌收费标准">
                <el-option
                  v-for="item in hpList"
                  :key="item.id"
                  :label="item.feeRuleName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入场记录匹配类型  " prop="enterMatchType">
              <el-radio-group v-model="dialogForm.enterMatchType">
                <el-radio :label="1">关闭</el-radio>
                <el-radio :label="2">车牌模糊匹配</el-radio>
                <el-radio :label="3">最近的停车记录匹配</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="是否测试停车场" prop="testFlag">
              <el-select v-model="dialogForm.testFlag" clearable placeholder="请选择是否测试停车场" style="width:100%;">
                <el-option
                  v-for="item in dict.type.EYesOrNo"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogForm.enterMatchType == 2" :span="12">
            <el-form-item label="车牌模糊匹配误差值  " prop="enterMatchDeviation">
              <el-input v-model="dialogForm.enterMatchDeviation" clearable class="filter-item" placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 地图弹窗 -->
    <mapLog ref="mapLog" @mapSubmit="mapSubmit" isDetail :formType="{
      'longitude':'longitude',
      'latitude':'latitude',
      'details':'address',
    }"></mapLog>
  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { fetchList, deletePark, createPark, updatePark, parkDetail } from '@/api/park'
import { getTempRules } from '@/api/tempRule'
import { getDepartmentList } from '@/api/base'
import { getData, } from '@/api/system/dictionary'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { listOrgs } from '@/api/system/organization'
import mapLog from "@/components/mapLog";

export default {
  name: 'Park',
  components: { Pagination,mapLog },
  dicts: ['EYesOrNo','EParkingType'],
  data() {
    return {
      suoche:false,
      shichang:0,
      danducharge: [], // 新能源是否单独收费数据
      list: null,
      total: 0,
      listLoading: true,
      status_options: [{
        value: '',
        label: '全部'
      }, {
        value: '1',
        label: '启用'
      }, {
        value: '2',
        label: '停用'
      }],
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogTitle: '温馨提示',
      dialogFormVisible: false,
      dialogForm: { ignoreDebt: null, tempRuleId: null },
      dialogType: 1,
      name: '',
      deleteParkId: 0,
      tempRuleList: [],
      parkList: [],
      departmentList: [],
      formRules: {
        newEnergyTempRuleFlag: [{ required: true, message: '请选择新能源是否单独收费', trigger: 'blur' }],
        yellowLicenseTempRuleFlag: [{ required: true, message: '请选择黄牌车是否单独收费', trigger: 'blur' }],
        name: [{ required: true, message: '请输入停车场名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入停车场地址', trigger: 'blur' }],
        businessCharge: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        businessPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        spaceCount: [{ required: true, message: '请输入总车位数', trigger: 'blur' }],
        staticSpaceCount: [{ required: true, message: '请输入固定车位数', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构名称', validator: this.checkSelected, trigger: 'change' }],
        area: [{ required: true, message: '请输入所属城市', trigger: 'blur' }],
        // tempRuleId: [{ required: true, message: '请选择收费规则', trigger: 'blur' }],
        ignoreDebtTypes: [{ required: true, message: '请选择欠费是否可进', trigger: 'blur' }],
        parkingTypes: [{ required: true, message: '请选择可停放类型', trigger: 'blur' }],
        unionPayment: [{ required: true, message: '请选择是否合并路侧欠费', trigger: 'blur' }],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入维度', trigger: 'blur' }],
        enterMatchType: [{ required: true, message: '请选择入场记录匹配类型', trigger: 'change' }],
        testFlag: [{ required: true, message: '请选择是否测试停车场', trigger: 'change' }],
        enterMatchDeviation: [{ required: true, message: '请输入车牌模糊匹配误差值', trigger: 'blur' }],
				organizationId: [{ required: true, message: '请选择组织', validator: this.checkSelected, trigger: 'change' }],
      },
      amapOpen: false,
      oAddMapPlaceSearch: null, // 地图查询服务
      aPoiSearchOptions: [], // 可选择地图列表
      bPoiSearchLoading: false, // 地图搜索 loading
      // 地图form
      smapForm: {},
      xnyList: [],// 新能源数据
      hpList:[],//换牌数据
			orangeList:[],//组织数据
    }
  },
  created() {
    this.getDepartmentList()
    this.getList()
		this.getData()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
		async getData(){//新能源是否单独收费数据
			let res = await getData('EYesOrNo')
			let list = res.data || []
			this.danducharge = list
		},
    async listOrgs(departmentId){//根据机构获取组织
      let res = await listOrgs({departmentId})
			let list = res.data || []
			this.orangeList = [...list]
		},
    handleChange(key) {
      return (val) => {
        if (val.includes(1)) {
          this.dialogForm[key] = [1]
        }
      }
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getStatus(status) {
      if (status == 1) {
        return '启用'
      }
      return '停用'
    },
    deletePark(name, parkId) {
      this.$confirm(`您确定删除停车场：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePark({ id: parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    reset(){
      this.tempRuleList = []
      this.xnyList = []
      this.hpList = []
       this.parkList = []
       this.dialogForm = {}
       this.$nextTick(() => {
         this.$refs.dialogForm.clearValidate()
       })
    },
    startAdd() {
      this.dialogFormVisible = true
      this.dialogType = 1
			this.orangeList = []
      this.reset()
      this.getDepartmentList()
    },

    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType == 1) {
            createPark(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updatePark(this.dialogForm).then(response => {
               this.$message({
                 message: '修改成功!',
                 type: 'success'
               })
               this.getList()
               this.dialogFormVisible = false
               this.dialogForm = {}
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getTempRules(departmentId, type) {
      getTempRules({ departmentId, type }).then(response => {
        let data = response.data || []
        if (type == 1) this.tempRuleList = data
        if (type == 2) this.xnyList = data
        if(type == 4) this.hpList = data
      })
    },
    handleDepartChange(val) {
      let dialogForm = {...this.dialogForm}
      dialogForm.tempRuleId = ''
      dialogForm.newEnergyTempRuleId = ''
      dialogForm.yellowLicenseTempRuleId = ''
      dialogForm.pid = ''
			dialogForm.organizationId = ''
      this.dialogForm = {...dialogForm}
      this.getTempRules(val, 1)
      this.getTempRules(val, 2)
      this.getTempRules(val, 4)
      this.selectDepartmentId(val)
			this.listOrgs(val)
    },
    async startEditPark(row) {//修改
      this.dialogFormVisible = true
      this.reset()
      this.getTempRules(row.departmentId, 1)
      this.getTempRules(row.departmentId, 2)
      this.getTempRules(row.departmentId, 4)
			this.orangeList = []
			this.listOrgs(row.departmentId)
      this.selectDepartmentId(row.departmentId)
      const res = await parkDetail(row.id)
      const data = res.data
      this.dialogType = 2
      this.dialogForm = { ...data }
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      this.getDepartmentList()
    },
    selectDepartmentId(event) {
      this.parkList = [{ 'id': null, 'name': '无' }]
      for (var k = 0; k < this.departmentList.length; k++) {
        if (this.departmentList[k].id == event) {
          this.parkList.push.apply(this.parkList, this.departmentList[k].parks)
          return
        }
      }
    },
    mapSubmit(form){//地图弹窗提交
      this.dialogForm = {...form}
    },
    //地图打开
    amapSelect(){
      this.$refs.mapLog.mapLoad(this.dialogForm)
    },
  }

}
</script>
<style>
  .miao{
    width: 94px;height: 40px;border: 1px solid #707070;
    margin-left: 20px;
  }
.amap-icon img,.amap-icon,
.amap-marker-content img{
    width: 25px!important;
    height: 34px!important;
}
</style>
<style scoped>
#container {width:100%; height: 300px; }
</style>
